#include "stdafx.h"
#include "logger.h"

#ifndef INVALID_FILE_ATTRIBUTES
    #define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
#endif

// logging support
Logger theLogger;
Logger::Logger()
: m_hFile(NULL)
{
    // to turn this on, create the file vc1encoder.log in the temp directory
	DWORD dwBufSize=512;
	WCHAR lpPathBuffer[512];
	GetTempPath(dwBufSize, lpPathBuffer);
	WCHAR pFile[512];
	wsprintf(pFile, L"%s\\vc1encoder.log", lpPathBuffer);

    if (GetFileAttributes(pFile) != INVALID_FILE_ATTRIBUTES)
    {
        m_hFile = CreateFile(pFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, 0, NULL);
        if (m_hFile == INVALID_HANDLE_VALUE)
        {
            m_hFile = NULL;
        } else
        {
            SetFilePointer(m_hFile, 0, NULL, FILE_END);
        }

        SYSTEMTIME st;
        GetLocalTime(&st);
		Log(L"Started %04d-%02d-%02d %02d:%02d:%02d",
            st.wYear,
            st.wMonth,
            st.wDay,
            st.wHour,
            st.wMinute,
            st.wSecond);
    }
}

Logger::~Logger()
{
    if (m_hFile != NULL)
    {
        CloseHandle(m_hFile);
    }
}

void 
Logger::Log(const WCHAR* pFormat, ...)
{
    if (m_hFile != NULL)
    {
        va_list va;
        va_start(va, pFormat);
        WCHAR  ach[4096];
        int cch = vswprintf(ach, pFormat, va);
        va_end(va);

        ach[cch++] = '\r';
        ach[cch++] = '\n';

        //CAutoLock lock(&m_csLog);
        DWORD cActual;
        WriteFile(m_hFile, ach, cch * sizeof(WCHAR), &cActual, NULL);
    }
}